#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
WordMathMerger插件主入口
提供命令行界面和图形界面两种使用方式
"""

import sys
import os
import argparse
from pathlib import Path

# 添加插件路径到系统路径
plugin_dir = Path(__file__).parent
sys.path.insert(0, str(plugin_dir))

from src.WordMathMerger import WordMathMerger

def cli_merge():
    """命令行界面"""
    parser = argparse.ArgumentParser(description='WordMathMerger - Word文档数学内容合并工具')
    parser.add_argument('main_doc', help='主文档路径')
    parser.add_argument('docs', nargs='+', help='要合并的文档路径列表')
    parser.add_argument('-o', '--output', default='merged_output.docx', help='输出文件路径')
    parser.add_argument('-v', '--verbose', action='store_true', help='显示详细日志')
    
    args = parser.parse_args()
    
    merger = WordMathMerger()
    merger.verbose = args.verbose
    
    try:
        result = merger.merge_documents(args.main_doc, args.docs, args.output)
        if result:
            print(f"✅ 合并成功！输出文件：{args.output}")
        else:
            print("❌ 合并失败！")
            sys.exit(1)
    except Exception as e:
        print(f"❌ 错误：{e}")
        sys.exit(1)

def gui_merge():
    """简单的图形界面"""
    try:
        import tkinter as tk
        from tkinter import filedialog, messagebox, ttk
        
        def select_main():
            filename = filedialog.askopenfilename(
                title="选择主文档",
                filetypes=[("Word文档", "*.docx"), ("所有文件", "*.*")]
            )
            if filename:
                main_entry.delete(0, tk.END)
                main_entry.insert(0, filename)
        
        def select_docs():
            filenames = filedialog.askopenfilenames(
                title="选择要合并的文档",
                filetypes=[("Word文档", "*.docx"), ("所有文件", "*.*")]
            )
            if filenames:
                docs_listbox.delete(0, tk.END)
                for filename in filenames:
                    docs_listbox.insert(tk.END, filename)
        
        def merge_docs():
            main_doc = main_entry.get()
            if not main_doc:
                messagebox.showerror("错误", "请选择主文档！")
                return
            
            docs = docs_listbox.get(0, tk.END)
            if not docs:
                messagebox.showerror("错误", "请选择要合并的文档！")
                return
            
            output = filedialog.asksaveasfilename(
                title="保存合并后的文档",
                defaultextension=".docx",
                filetypes=[("Word文档", "*.docx"), ("所有文件", "*.*")]
            )
            if output:
                merger = WordMathMerger()
                merger.verbose = True
                try:
                    result = merger.merge_documents(main_doc, list(docs), output)
                    if result:
                        messagebox.showinfo("成功", f"合并完成！\n输出文件：{output}")
                    else:
                        messagebox.showerror("失败", "合并失败！")
                except Exception as e:
                    messagebox.showerror("错误", f"合并出错：{str(e)}")
        
        # 创建主窗口
        root = tk.Tk()
        root.title("WordMathMerger 插件")
        root.geometry("600x500")
        
        # 主文档选择
        tk.Label(root, text="主文档:").pack(pady=5)
        main_frame = tk.Frame(root)
        main_frame.pack(pady=5)
        main_entry = tk.Entry(main_frame, width=50)
        main_entry.pack(side=tk.LEFT, padx=5)
        tk.Button(main_frame, text="选择", command=select_main).pack(side=tk.LEFT)
        
        # 要合并的文档
        tk.Label(root, text="要合并的文档:").pack(pady=5)
        docs_frame = tk.Frame(root)
        docs_frame.pack(pady=5)
        docs_listbox = tk.Listbox(docs_frame, width=60, height=10)
        docs_listbox.pack(side=tk.LEFT, padx=5)
        scrollbar = tk.Scrollbar(docs_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        docs_listbox.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=docs_listbox.yview)
        
        tk.Button(root, text="添加文档", command=select_docs).pack(pady=5)
        tk.Button(root, text="开始合并", command=merge_docs, bg="green", fg="white").pack(pady=20)
        
        root.mainloop()
        
    except ImportError:
        print("图形界面需要tkinter支持，使用命令行模式")
        cli_merge()

if __name__ == "__main__":
    if len(sys.argv) > 1:
        cli_merge()
    else:
        gui_merge()